package idv.nightpig.lab02.web.action;

import idv.nightpig.lab02.domain.User;
import idv.nightpig.lab02.service.Lab02Service;
import idv.nightpig.lab02.web.util.SessionKey;

import java.util.Map;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;

@Component
@Scope("prototype")
@InterceptorRefs( { @InterceptorRef("defaultStack") })
public class LoginAction extends ActionSupport {

    private static final long serialVersionUID = 1L;
    private String account;
    @Autowired
    private Lab02Service lab02Service;
    private String password;

    public String getAccount() {
        return account;
    }

    public String getPassword() {
        return password;
    }

    @Action(value = "login", results = { @Result(name = "success", type = "redirectAction", location = "user") })
    public String index() {
        Map<String, Object> session = ActionContext.getContext().getSession();
        User user = lab02Service.doLogin(account, password);
        session.put(SessionKey.USER.toString(), user);
        return (user != null) ? "success" : "login";
    }

    @RequiredStringValidator(message = "required", trim = true)
    public void setAccount(String account) {
        this.account = account;
    }

    @RequiredStringValidator(message = "required", trim = true)
    public void setPassword(String password) {
        this.password = password;
    }

}
